package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.*;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.query.StrategyQuery;
import cn.wolfcode.wolf2w.redis.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.repository.StrategyCatalogRepository;
import cn.wolfcode.wolf2w.repository.StrategyRepository;
import cn.wolfcode.wolf2w.repository.StrategyThemeRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Service
public class StrategyServiceImpl implements IStrategyService {

    @Autowired
    private MongoTemplate template;

    @Autowired
    private StrategyRepository repository;

    @Autowired
    private StrategyCatalogRepository strategyCatalogRepository;

    @Autowired
    private StrategyThemeRepository strategyThemeRepository;

    @Autowired
    private IDestinationService destinationService;

    @Override
    public void save(Strategy strategy) {

    }

    @Override
    public void delete(String id) {

    }

    @Override
    //page对象里面包括: 总页数 每页显示条数......
    public Page<Strategy> query(StrategyQuery qo) {
        //PageResult 7核心属性
        //核心: count  list
        //使用template方式只能返回list, 需要将list分装成pagte对象

        //1: 查询总数:total
        Query query = new Query();
        long total = template.count(query, Strategy.class);
        if(total == 0){
            return Page.empty();  //当查询条数为0时则返回为空
        }
        //2: 设置分页相关数据 以及返回数据
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.DESC, "_id");
        query.with(pageable);
        List<Strategy> list = template.find(query, Strategy.class);

        //3:封装page对象
        return new PageImpl<Strategy>(list,pageable,total);
    }

    @Override
    public List<Strategy> getViewnumTop3(String destId) {
        //点击量前3
        Query query = new Query();
        Pageable of = PageRequest.of(0, 3, Sort.Direction.DESC, "viewnum");
//        query.addCriteria()
        query.with(of);
        List<Strategy> list = template.find(query, Strategy.class);
        return list;
    }

    @Override
    public List<Strategy> getStrategyByCatalogId(String id) {
        return repository.findByCatalogId(id);
    }


    @Override
    public void saveOrUpdate(Strategy strategy) {
        String catalogId = strategy.getCatalogId();
        Optional<StrategyCatalog> strategyCatalog = strategyCatalogRepository.findById(catalogId);
        String destId = strategyCatalog.get().getDestId();
        strategy.setDestId(destId);
        String destName = strategyCatalog.get().getDestName();
        strategy.setDestName(destName);
        String catalogName = strategyCatalog.get().getName();
        strategy.setCatalogName(catalogName);
        String themeName = strategyThemeRepository.findById(strategy.getThemeId()).get().getName();
        strategy.setThemeName(themeName);
        List<Destination> toasts = destinationService.getToasts(strategyCatalog.get().getDestId());
        if (toasts != null && toasts.size() > 0){
            if("中国".equals(toasts.get(0).getName())){
                strategy.setIsabroad(Strategy.ABROAD_NO);
            }else{
//                strategy.setIsabroad(Strategy.ABROAD_YES);
            }
        }
        if(!StringUtils.hasLength(strategy.getId())){
            //添加
            strategy.setId(null);
            //5:创建时间
            strategy.setCreateTime(new Date());
            repository.save(strategy);
        }else{
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(strategy.getId()));
            DBHelper.update(template, query, strategy,
                    "destId","destName","themeId",
                    "themeName","catalogId","catalogName",
                    "title","subTitle","summary","coverUrl",
                    "isabroad","state","content");

        }
    }


    @Override
    public Strategy findById(String sid) {
        return repository.findById(sid).get();
    }

    @Override
    public List<Strategy> list() {
        return repository.findAll();

    }

    @Override
    public void updateStatisVo(StrategyStatisVO vo) {

        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(vo.getStrategyId()));


        //DBHelper 工具类中共需要明确指定表名， 集合名，Strategy类字节码可以找到
        Strategy strategy = new Strategy();
        BeanUtils.copyProperties(vo, strategy);

        DBHelper.update(template, query, strategy, "favornum",
                "replynum","sharenum","thumbsupnum","viewnum");
    }

    @Override
    public List<Strategy> findByDestName(String keyword) {
        return repository.findByDestName(keyword);

    }

    @Override
    public Strategy get(String id) {
        return repository.findById(id).get();
    }
}
